<template>
  <div>
    <div class="i_bg">
      <div class="content mar_20">
        <img src="@/assets/images/img2.jpg" />
      </div>

      <!--Begin 第二步：确认订单信息 Begin -->
      <div class="content mar_20">
        <div class="two_bg">
          <div class="two_t">
            <span class="fr"><a href="#">修改</a></span
            >商品列表
          </div>
          <table
            border="0"
            class="car_tab"
            style="width: 1110px"
            cellspacing="0"
            cellpadding="0"
          >
            <tr>
              <td class="car_th" width="550">商品名称</td>
              <td class="car_th" width="140">价格</td>
              <td class="car_th" width="150">购买数量</td>
              <td class="car_th" width="130">小计</td>
            </tr>
            <tr v-for="(item, index) in cartList" :key="index">
              <td>
                <div class="c_s_img">
                  <img
                    :src="`http://117.72.153.227/image/${item.fileName}`"
                    width="73"
                    height="73"
                  />
                </div>
                {{ item.productName }}
              </td>
              <td align="center">￥{{ item.price }}</td>
              <td align="center">{{ item.quantity }}</td>
              <td align="center" style="color: #ff4e00">
                ￥{{ (item.price * item.quantity).toFixed(2) }}
              </td>
            </tr>
            <tr>
              <td
                colspan="5"
                align="right"
                style="font-family: 'Microsoft YaHei'"
              >
                商品总价：￥{{ totalPrice.toFixed(2) }}
              </td>
            </tr>
          </table>

          <div class="address-selector">
            <select v-model="selectedAddressId" @change="updateSelectedAddress">
              <option value="">请选择收货地址</option>
              <option
                v-for="address in addressList"
                :key="address.id"
                :value="address.id"
              >
                {{ address.recipient }} - {{ address.mobile }} -
                {{ address.address }}{{ address.DetailedAddress }}
                <span v-if="address.isDefault === 1">(默认)</span>
              </option>
            </select>

            <!-- 显示选中的地址详情 -->
            <div v-if="selectedAddress" class="address-details">
              <p><strong>收货人：</strong>{{ selectedAddress.recipient }}</p>
              <p><strong>联系电话：</strong>{{ selectedAddress.mobile }}</p>
              <p>
                <strong>收货地址：</strong>{{ selectedAddress.address
                }}{{ selectedAddress.DetailedAddress }}
              </p>
            </div>

            <div v-else class="address-notice">请先选择收货地址</div>
          </div>
          <table
            border="0"
            style="width: 900px; margin-top: 20px"
            cellspacing="0"
            cellpadding="0"
          >
            <tr height="70">
              <td align="right">
                <b style="font-size: 14px"
                  >应付款金额：<span style="font-size: 22px; color: #ff4e00"
                    >￥{{ totalPrice.toFixed(2) }}</span
                  ></b
                >
              </td>
            </tr>
            <tr height="70">
              <td align="right">
                <a href="#" @click.prevent.once="CreateOrder"
                  ><img src="@/assets/images/btn_sure.gif"
                /></a>
              </td>
            </tr>
          </table>
        </div>
      </div>

      <!--End 第二步：确认订单信息 End-->
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "BuyCarTwo",
  data() {
    return {
      cartList: [],
      totalPrice: 0,
      addressList: [], // 收货地址列表
      selectedAddressId: null, // 地址ID
      selectedAddress: null, // 地址详情
    };
  },
  created() {
    this.loadCartData();
    this.loadUserAddresses();
  },
  methods: {
    // 加载购物车数据
    async loadCartData() {
      try {
        const token = sessionStorage.getItem("token");
        if (!token) {
          this.$router.push("/login");
          return;
        }

        const response = await axios.get(
          `/api/shoppingCart/getShoppingCart`
        );

        if (response.data.code === 200) {
          this.cartList = response.data.list;
          this.calculateTotal();
        }
      } catch (error) {
        console.error("加载购物车出错:", error);
      }
    },
    async loadUserAddresses() {
      try {
        const token = sessionStorage.getItem("token");
        if (!token) return;

        const response = await axios.get(
          `/api/address/getAllAddress`
        );
        if (response.data.code === 200) {
          this.addressList = response.data.data;
          // 默认选中默认地址
          const defaultAddress = this.addressList.find(
            (addr) => addr.isDefault === 1
          );
          if (defaultAddress) {
            this.selectedAddressId = defaultAddress.id;
            this.selectedAddress = defaultAddress;
          }
        }
      } catch (error) {
        console.error("加载收货地址出错:", error);
      }
    },

    // 更新选中的地址
    updateSelectedAddress() {
      this.selectedAddress = this.addressList.find(
        (addr) => addr.id === this.selectedAddressId
      );
    },
    async CreateOrder() {
      // 验证收货地址
      if (!this.selectedAddressId) {
        this.$message.error("请选择收货地址");
        return;
      }

      // 验证购物车
      if (this.cartList.length === 0) {
        this.$message.error("购物车中没有商品");
        return;
      }

      this.loading = true;
      try {
        const token = sessionStorage.getItem("token");
        if (!token) {
          alert("请先登录");
          this.$router.push("/login");
          return;
        }

        // 构造订单商品数据
        const orderItems = {};
        this.cartList.forEach((item) => {
          orderItems[item.productId] = item.quantity;
        });

        // 调用创建订单接口
        const response = await axios.post(
          "/api/order/createOrder",
          orderItems,
          {
            params: {
              addressId: this.selectedAddressId,
            },
          }
        );

        if (response.data.code === 200) {
          this.$message.success("订单创建成功");
          // 跳转到订单支付页面或订单详情页
          this.$router.push(`/UserOrderList`);
        } else {
          this.$message.error(response.data.msg || "订单创建失败");
        }
      } catch (error) {
        console.error("创建订单出错:", error);
        this.$message.error("创建订单失败，请稍后重试");
      } finally {
        this.loading = false;
      }
    },
    // 计算商品总价
    calculateTotal() {
      this.totalPrice = this.cartList.reduce((total, item) => {
        return total + item.price * item.quantity;
      }, 0);
    },
  },
};
</script>

<style scoped>
/* 简化版地址选择器样式 - 橙色主题 */
.address-selector {
  margin: 20px 0;
  padding: 15px;
  background: #fff8f0;
  border: 1px solid #ffd8b1;
}

.address-selector select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ffa940;
  font-size: 14px;
  color: #666;
  background-color: #fff;
}

/* 地址详情样式 */
.address-details {
  margin-top: 15px;
  padding: 10px;
  background: #fff;
  border: 1px solid #ffd8b1;
}

.address-details p {
  margin: 5px 0;
  color: #666;
}

.address-details p strong {
  color: #ff6700;
}

/* 地址提示样式 */
.address-notice {
  margin-top: 15px;
  padding: 10px;
  text-align: center;
  color: #ff6700;
  background: #fff;
  border: 1px dashed #ffa940;
}

/* 保持原有基本样式 */
.two_bg {
  background: #fff;
  padding: 20px;
}

.two_t {
  height: 38px;
  line-height: 38px;
  border-bottom: 1px solid #e4e4e4;
  margin-bottom: 15px;
}

.car_tab {
  border: 1px solid #e4e4e4;
}

.car_th {
  background: #f5f5f5;
  text-align: center;
}

.c_s_img {
  float: left;
  margin-right: 10px;
}

.pay li.checked {
  border-color: #ff4e00;
}
</style>